package blog.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.service.CategoryService;

import blog.entity.Category;

@Controller
@RequestMapping("/admin/category")
public class CategoryController {
	@Autowired
	private  CategoryService categoryService;
	
	/**
	 * 	获取所有分类及其相关信息
	 * @return
	 */
	@RequestMapping("")
	private String getAll(Map<String,Object> model){
		//获取所有分类及其相关信息
		List<Category> categoryList = categoryService.listCategoryInfo();
		model.put("categoryList", categoryList);
		return "Category/category-list";
	}
	/**
	 * 	根据父分类id查询下面的所有子分类
	 * @param parentCateId
	 * @return json格式数据
	 */
	@RequestMapping ("/listsub") 
	@ResponseBody
	private List<Category> listsub(Integer parentCateId){	
		return categoryService.listSub(parentCateId);
	}
	/**
	 * 	添加分类
	 * 	发现bug：添加的分类名不能重复，且目前没有验证分类名是否重复的操作
	 * @return
	 */
	@RequestMapping(value = "/add",method = RequestMethod.POST)
	private String addCategory(Category category) {
		//添加操作
		categoryService.addCategory(category);
		//返回列表展示
		return "forward:/admin/category";
	}
	
	/**
	 * 	删除分类
	 * @param categoryId
	 * @return
	 */
	@RequestMapping("/delete/{categoryId}")
	private String deleteCategory(@PathVariable Integer categoryId) {
		//删除操作
		categoryService.deleteCategoryById(categoryId);
		//返回列表展示
		return "forward:/admin/category";
	}
	
	/**
	 * 	去编辑分类页面
	 * @param categoryId
	 * @return
	 */
	@RequestMapping(value = "/edit/{categoryId}",method = RequestMethod.GET)
	private String goEditCategory(@PathVariable Integer categoryId,Map<String,Object> model) {
		//查询分类信息
		Category category = categoryService.getCategoryById(categoryId);
		//获取所有分类及其相关信息
		List<Category> categoryList = categoryService.listCategoryInfo();
		//查询分类下子分类的数量
		int count = categoryService.getCategoryCount(category.getCategoryId());
		//传到修改页面
		model.put("category", category);
		model.put("categoryList", categoryList);
		model.put("count", count);
		return "Category/category-edit";
	}
	
	/**
	 * 	编辑分类
	 * @param categoryId
	 * @return
	 */
	@RequestMapping(value = "/edit",method = RequestMethod.POST)
	private String editCategory(Category category) {
		//执行修改操作
		categoryService.editCategory(category);
		return "forward:/admin/category";
	}
	
	
}
